package com.kit.data.kitopeso.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.JsonObject;
import com.kit.data.kitopeso.PathMaping;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseDialog;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoCodeActivityBinding;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.obj.KitoMessageInfo;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.PhoneUtils;
import com.kit.data.kitopeso.tools.PopUtils;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.SpUtils;
import com.kit.data.kitopeso.tools.Tools;
import com.kit.data.kitopeso.tools.ViewUtils;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoCodeActivity extends BaseActivity<KitoCodeActivityBinding> {

    int type = 1;

    String phoneNumber;

    String mobileEditFlag;

    int codeTime = 0;

    private final int GET_CODE_WHAT = 1;

    private final int RESET_CODE_WHAT = 2;

    boolean isBirth;

    String needSubmitBirthDay;

    String submitBirthDay;


    @Override
    protected KitoCodeActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoCodeActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {
        phoneNumber = getIntent().getStringExtra("phoneNumber");
        mobileEditFlag = getIntent().getStringExtra("mobileEditFlag");

        LogUtil.e("me","mobileEditFlag->"+mobileEditFlag);

        binding.tvInput1.setType(PU.P72);

        binding.tvInput2.setType(PU.P73);

        binding.tvInput1.setText(phoneNumber);
        binding.tvInput1.setInputType(InputType.TYPE_NULL);

        binding.tvEdit.setVisibility(View.VISIBLE);
        binding.tvBtn1.setVisibility(View.GONE);
        binding.tvBtn1.setSelected(true);

        binding.tvEdit.setOnClickListener(v -> {
            LogUtil.e("me", "codeTime->" + codeTime);
            if (codeTime <= 0) {
                ViewUtils.viewScale(v);
                binding.tvInput1.setInputType(InputType.TYPE_CLASS_NUMBER);
                binding.tvEdit.setVisibility(View.GONE);
                binding.tvBtn1.setVisibility(View.VISIBLE);

                binding.tvBtn2.setSelected(false);
                binding.tvBtn2.setClickable(false);

                binding.tvInput1.setSelected(true);
                LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.weight=1;
                layoutParams.rightMargin=ResUtils.d(R.dimen.dp_8);
                binding.tvInput1.setLayoutParams(layoutParams);


                Tools.showKeyboard(binding.tvInput1);

                String data = binding.tvInput1.getText().toString();
                if (!TextUtils.isEmpty(data)) {
                    binding.tvInput1.setSelection(data.length());
                }




                binding.tvInput1.setCursorVisible(true);
                binding.tvInput1.requestFocus();

                PU.userBuriedPoint(PU.P75, "");

            }
        });

        binding.tvBtn1.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P76, "");
            String str = binding.tvInput1.getText().toString();
            boolean isPhoneNumber = PhoneUtils.isPhoneNumber(str);
            if (!isPhoneNumber) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_input_hit));
                return;
            }
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput1);
            binding.tvEdit.setVisibility(View.VISIBLE);
            binding.tvBtn1.setVisibility(View.GONE);
            binding.tvInput1.setInputType(InputType.TYPE_NULL);

            binding.tvBtn2.setSelected(true);
            binding.tvBtn2.setClickable(true);

            binding.tvInput1.setCursorVisible(false);
            binding.tvInput1.clearFocus();

            binding.tvInput1.setSelected(false);
            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.rightMargin=ResUtils.d(R.dimen.dp_8);
            binding.tvInput1.setLayoutParams(layoutParams);

        });

        binding.typeLayout1.setOnClickListener(v -> {
            if (binding.tvBtn2.isSelected()) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P77, "");
                type = 1;
                switchType();
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput1);
            }
        });

        binding.typeLayout2.setOnClickListener(v -> {
            if (binding.tvBtn2.isSelected()) {
                ViewUtils.viewScale(v);
                type = 2;
                switchType();
                PU.userBuriedPoint(PU.P78, "");
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput1);
            }
        });

        binding.tvBtn2.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P79, "");
            if (binding.tvBtn2.isSelected()) {
                sendWhatAppMessage();
            }
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput1);
        });


        binding.tvBtn.setOnClickListener(v -> {
            if (binding.tvBtn.isSelected()) {
                ViewUtils.viewScale(v);
                PU.userBuriedPoint(PU.P80, "");
                PU.userBuriedAllPoint(getActivity());


                if (isBirth) {
                    showBirthTipsDialog();
                } else {
                    checkWhatAppMessageCode();
                }
            }
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvInput1);
        });

        binding.tvInput2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    binding.tvBtn.setSelected(true);
                    binding.tvBtn.setClickable(true);
                } else {
                    binding.tvBtn.setSelected(false);
                    binding.tvBtn.setClickable(false);
                }

                if (binding.tvInput2.isProgrammaticChange()) {
                    String str = String.valueOf(s);
                    binding.tvInput2.setSelected(!TextUtils.isEmpty(str));
                    binding.tvBtn2.setSelected(true);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        binding.tvInput1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (binding.tvInput1.isProgrammaticChange()) {
                    String str = String.valueOf(s);
                    binding.inputLayout1.setSelected(!TextUtils.isEmpty(str));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        binding.getRoot().setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));

        binding.tvHit.setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.tvHit));

        binding.tvSubTitle1.setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.tvSubTitle1));


        binding.tvRoot.setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.tvRoot));


        binding.tvBtn.setSelected(false);

        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            startActivity(new Intent(getActivity(), KitoCustomerServiceActivity.class));
        });

        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });


    }

    @Override
    protected void initData() {

        UP_TYPE1 = PU.P70;
        UP_TYPE2 = PU.P71;

        if (TextUtils.isEmpty(mobileEditFlag) || mobileEditFlag.equals("YES")) {
            binding.tvEdit.setVisibility(View.VISIBLE);
        } else {
            binding.tvEdit.setVisibility(View.GONE);
        }

        if (mHandler != null) {
            mHandler.sendEmptyMessage(RESET_CODE_WHAT);
        }

        switchType();
    }

    void switchType() {
        if (type == 1) {

            binding.tvSubTitle1.setText(ResUtils.s(R.string.code_type_title1));

            binding.typeLayout1.setSelected(true);
            binding.tvIcon1.setSelected(true);
            binding.tvTitle1.setSelected(true);

            binding.typeLayout2.setSelected(false);
            binding.tvIcon2.setSelected(false);
            binding.tvTitle2.setSelected(false);
        } else {

            binding.tvSubTitle1.setText(ResUtils.s(R.string.code_type_title2));

            binding.typeLayout1.setSelected(false);
            binding.tvIcon1.setSelected(false);
            binding.tvTitle1.setSelected(false);

            binding.typeLayout2.setSelected(true);
            binding.tvIcon2.setSelected(true);
            binding.tvTitle2.setSelected(true);
        }
    }


    void sendWhatAppMessage() {
        phoneNumber = binding.tvInput1.getText().toString();
        if (!PhoneUtils.isPhoneNumber(phoneNumber)) {
            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_input_hit));
            return;
        }
        showLoading("");
        codeTime = 60;
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(GET_CODE_WHAT, 1000);
        }

        String sendType = "SMS";
        if (type != 1) {
            sendType = "WHATSAPP";
        }

        LogUtil.e("me", sendType + "--phoneNumber--" + phoneNumber);

        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[3]);
        json.addProperty("mobile", phoneNumber);
        json.addProperty("submitMobile", phoneNumber);
        json.addProperty("sendType", sendType);

        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_PRODUCT);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "--sendWhatAppMessage--" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {

                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "sendWhatAppMessage->" + json1);
                            if (JsonParse.getCode(json1)) {
                                KitoMessageInfo message = JsonParse.sendWhatAppMessageJson2Obj(json1);
                                if (message != null) {
                                    needSubmitBirthDay = message.getNeedSubmitBirthDay();
                                    LogUtil.e("me", "needSubmitBirthDay->" + needSubmitBirthDay + "->" + message.getDirectLoginFlag());
                                    if (!TextUtils.isEmpty(message.getDirectLoginFlag()) && message.getDirectLoginFlag().equals("YES")) {
                                        finish();
                                    } else {
                                        if (!TextUtils.isEmpty(needSubmitBirthDay) && needSubmitBirthDay.equals("YES")) {
                                            showBirthDialog();
                                        }
                                    }
                                }
                                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_send_hit1));
                            } else {
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(RESET_CODE_WHAT);
                                }
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtil.e("me", "sendWhatAppMessage->" + e.toString());
                        hideLoading();
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(RESET_CODE_WHAT);
                        }
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_send_hit2));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });

    }


    void showBirthDialog() {
        PopUtils.showBirthPop(getActivity(), binding.getRoot(), new PopUtils.PopClickInterface1() {
            @Override
            public void onClickListener(String title, String value) {
                if (!TextUtils.isEmpty(value)) {
                    submitBirthDay = value;
                    LogUtil.e("me", "submitBirthDay->" + submitBirthDay);
                    isBirth = true;
                }
            }
        });
    }

    void showBirthTipsDialog() {
        showTipsDialog("", "", ResUtils.s(R.string.code_btn1), ResUtils.s(R.string.code_birth_hit), true, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                checkWhatAppMessageCode();
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
    }

    void checkWhatAppMessageCode() {
        phoneNumber = binding.tvInput1.getText().toString();
        String code = binding.tvInput2.getText().toString();
        if (!PhoneUtils.isPhoneNumber(phoneNumber)) {
            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_input_hit));
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.code_check_hit1));
            return;
        }

        if (!TextUtils.isEmpty(needSubmitBirthDay) && needSubmitBirthDay.equals("YES") && TextUtils.isEmpty(submitBirthDay)) {
            showBirthDialog();
            return;
        }

        showLoading("");


        String sendType = "SMS";
        if (type != 1) {
            sendType = "WHATSAPP";
        }

        if (needSubmitBirthDay == null) {
            needSubmitBirthDay = "";
        }


        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[4]);
        json.addProperty("mobile", phoneNumber);
        json.addProperty("submitMobile", phoneNumber);
        json.addProperty("checkType", sendType);
        json.addProperty("code", code);
        json.addProperty("needSubmitBirthDay", needSubmitBirthDay);



        if (!TextUtils.isEmpty(needSubmitBirthDay) && needSubmitBirthDay.equals("YES")) {
            json.addProperty("submitBirthDay", submitBirthDay);
        }
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-checkWhatAppMessageCode->" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "checkWhatAppMessageCode->" + json1);
                            if (JsonParse.getCode(json1)) {
                                finish();
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });

    }


    @SuppressLint("HandlerLeak")
    final
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@androidx.annotation.NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_CODE_WHAT:
                    mHandler.removeMessages(GET_CODE_WHAT);
                    codeTime = codeTime - 1;
                    binding.tvBtn2.setVisibility(View.VISIBLE);
                    if (codeTime > 0) {
                        binding.tvBtn2.setText(codeTime + "s");
                        binding.tvBtn2.setSelected(false);
                        binding.tvBtn2.setClickable(false);
                        mHandler.sendEmptyMessageDelayed(GET_CODE_WHAT, 1000);
                    } else {
                        codeTime = 0;
                        binding.tvBtn2.setText(getResources().getString(R.string.code_btn2));
                        binding.tvBtn2.setSelected(true);
                        binding.tvBtn2.setClickable(true);
                    }
                    break;
                case RESET_CODE_WHAT:
                    mHandler.removeMessages(GET_CODE_WHAT);
                    mHandler.removeMessages(RESET_CODE_WHAT);
                    codeTime = 0;
                    binding.tvBtn2.setText(getResources().getString(R.string.code_btn2));
                    binding.tvBtn2.setSelected(true);
                    binding.tvBtn2.setClickable(true);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(GET_CODE_WHAT);
        }
    }

}
